package com.zzu.base.common.pojo;

import com.zzu.base.entity.UserDO;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class LoginUser implements UserDetails {
    private UserDO user;
    private List<String> roles;
    private List<String> permissions;
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<>();
        if (roles != null) {
            authorities.addAll(roles.stream()
                    .filter(role -> !role.startsWith("ROLE_"))
                    .map(role -> "ROLE_" + role)
                    .map(SimpleGrantedAuthority::new)
                    .toList());
        }

        return authorities;
    }
    public Collection<? extends GrantedAuthority> getAuthPermissions() {
        List<GrantedAuthority> authorities = new ArrayList<>();
        if (permissions != null) {
            authorities.addAll(permissions.stream()
                    .map(SimpleGrantedAuthority::new)
                    .toList());
        }

        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return user.getStatus().getId()==0;
    }

    @Override
    public boolean isAccountNonLocked() {
        return user.getStatus().getId()==0;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return user.getStatus().getId()==0;
    }

    @Override
    public boolean isEnabled() {
        return user.getDeleted()==0;
    }
}